package com.ml.loan.common.valid;

import cn.hutool.core.util.ReUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 业务编码校验器（任意大小写字母或数字或下划线组合）
 *
 * @Author caozx
 * @Date 2021/4/9 19:00
 **/
public class IsBusinessCodeValidator implements ConstraintValidator<IsBusinessCode, String> {

    private boolean required = false;

    @Override
    public void initialize(IsBusinessCode constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(value)){
            return !required;
        }
        //任意大小写字母或数字或下划线组合
        return ReUtil.isMatch("^\\w+$", value);
    }
}
